﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;


namespace TImSdk
{
    public abstract class JsonCreationConverter<T> : JsonConverter
    {
        /// <summary>
        /// 这非常重要，否则序列化会中断！
        /// </summary>
        public override bool CanWrite
        {
            get
            {
                return false;
            }
        }
        /// <summary> 
        /// 根据JSON对象中的属性创建objectType的实例
        /// </summary> 
        /// <param name="objectType">预期对象的类型</param> 
        /// <param name="jObject">将反序列化的JSON对象的内容</param> 
        /// <returns></returns> 
        protected abstract T Create(Type objectType, JObject jObject);

        public override bool CanConvert(Type objectType)
        {
            return typeof(T).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType,
          object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;
            //从流加载JObject 
            JObject jObject = JObject.Load(reader);
            // 基于JObject创建目标对象
            T target = Create(objectType, jObject);
            // 填充对象属性
            serializer.Populate(jObject.CreateReader(), target);
            return target;
        }

        public override void WriteJson(JsonWriter writer, object value,
          JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }


    
}
